import speech_recognition as sr


# # 创建语音识别器对象
# r = sr.Recognizer()
#
# # 打开音频文件
# with sr.AudioFile('audio.wav') as source:
#     # 从音频文件中读取数据
#     audio_data = r.record(source)
#
# # 将音频转换为文字
# text = r.recognize_google(audio_data, language='zh-CN')
#
# # 打印转换结果
# print(text)


def reverse(file):
    r = sr.Recognizer()
    with sr.AudioFile(file) as source:
        audio_data = r.record(source)
    text = r.recognize_google(audio_data)
    return text


filePath = r"C:\Users\Administrator\Documents\WeChat Files\wxid_a8ll54i2gfk012\FileStorage\File\2023-09\U1 Reading.mp3"
print(reverse(filePath))
# # 实时获取麦克风中的音频转换为文本
# # def trans_micro_to_text():
# #     # 创建一个语音识别器对象
# #     recognizer = sr.Recognizer()
# #     text = "请开始讲话..."
# #     # 使用麦克风捕获实时音频
# #     with sr.Microphone() as source:
# #         print("请开始说话...")
# #         try:
# #             while True:
# #                 audio = recognizer.listen(source)
# #                 text = recognizer.recognize_google(audio, language="en-US")  # 使用Google Web Speech API进行识别
# #                 print("识别结果:", text)
# #         except KeyboardInterrupt:
# #             pass
# #     return text
# import speech_recognition as sr
# from flask import jsonify
# from pydub import AudioSegment
#
# from YuToBen.调用prompt的GPT接口 import prompt_gpt3
#
# # 创建一个语音识别器对象
# recognizer = sr.Recognizer()
#
# # 读取MP3音频文件
# audio_file = r"C:\Users\Administrator\Documents\WeChat Files\wxid_a8ll54i2gfk012\FileStorage\File\2023-09\U1 " \
#              r"Reading.mp3"
#
# # 转换MP3到WAV
# audio = AudioSegment.from_mp3(audio_file)
# audio.export(r"C:\Users\Administrator\Documents\WeChat Files\wxid_a8ll54i2gfk012\FileStorage\File\2023-09\temp.wav", format="wav")
#
# with sr.AudioFile(r"C:\Users\Administrator\Documents\WeChat Files\wxid_a8ll54i2gfk012\FileStorage\File\2023-09\temp.wav") as source:
#     audio_data = recognizer.record(source)
#     try:
#         text = recognizer.recognize_google(audio_data, language="en-US")
#         print(text)
#     except sr.UnknownValueError:
#         print(jsonify({"error": "Unable to transcribe audio"}))
#     except sr.RequestError as e:
#         print(jsonify({"error": str(e)}))
#
# # 使用语音识别器识别音频中的语音
# # with sr.AudioFile(audio_file) as source:
# #     audio_data = recognizer.record(source)  # 从音频文件中读取数据
# #     try:
# #         text = recognizer.recognize_google(audio_data, language="en-US")  # 使用Google Web Speech API进行识别
# #         print("转化为文本:", text)
# #     except sr.UnknownValueError:
# #         print("无法识别音频中的语音")
# #     except sr.RequestError as e:
# #         print(f"请求失败：{e}")
